<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/16
 * Time: 18:10
 */

namespace App\Process;


use App\Utility\HttpRequest;
use App\Utility\MTool;
use App\Utility\UUID;
use EasySwoole\Core\Component\Cache\Cache;
use EasySwoole\Core\Component\Di;
use EasySwoole\Core\Swoole\Process\AbstractProcess;
use EasySwoole\Core\Swoole\Time\Timer;
use Swoole\Exception;
use Swoole\Process;
use EasySwoole\Config;
use App\Sock\Logic\Game as GameLogic;
use EasySwoole\Core\Swoole\ServerManager;

class GameRound extends AbstractProcess
{

    protected $db;
    protected $timerId;
    protected $timerNId;
    protected $round_turn = 1;
    protected $start_time;
    protected $end_time;
    protected $round_time = 1 * 60;
    protected $open_time = 12;
    protected $curr_time;


    public function __construct(string $processName, array $args, bool $async = true)
    {
        $dbConf = Config::getInstance()->getConf('database');
        $this->db = Di::getInstance()->get('MYSQL');
        $this->db->setPrefix($dbConf['prefix']);
        $this->start_time = strtotime('10:00');
        $this->end_time = strtotime("01:55");
        $this->curr_time = time();
        parent::__construct($processName, $args, $async);
    }

    public function run(Process $process)
    {
        $round_cache = Cache::getInstance()->get('round_cache');
        $round_list = $round_cache['round_list'];
        $open_arr = [];
        foreach ($round_list as $item => $value) {
            $open_arr[$value['round_id']] = date('H:i', $value['open_time']);
        }


        // 每分钟
        $s = date('s');
        if ($s != 0) {
            $left = 60 - $s;
            Timer::delay($left * 1000, function () use ($open_arr, $round_list) {
                $temp_code = null;
                Timer::loop(60 * 1000, function () use ($open_arr, $round_list, &$temp_code) {
                    $date = date('H:i');
                    $index = array_search($date, $open_arr);
                    if (in_array($date, $open_arr)) {
                        $lottery_nums = $this->getOpenLottery();
                        $rs = $lottery_nums['number'];
                        $expect = $lottery_nums['expect'];

                        if ($temp_code == $expect) {
                            return false;
                        } else {
                            if ($expect != date('Ymd') . MTool::format_add($round_list[$index - 1]['round_circle'])) {
                                $this->timerNId = Timer::loop(6 * 1000, function () use ($index, $open_arr, $round_list) {
//                                    echo date('Ymd') . MTool::format_add($round_list[$index - 1]['round_circle']).PHP_EOL;

                                    $res = $this->getOpenLottery();

                                    $rs = $res['number'];
                                    $expect = $res['expect'];
//                                    echo 'except:'.$expect.PHP_EOL;

                                    if ($expect == date('Ymd') . MTool::format_add($round_list[$index - 1]['round_circle'])) {
                                        $this->saveLotteryCode($round_list, $index, $expect, $rs);
                                        Timer::clear($this->timerNId);
                                    }
                                });

                            } else {
                                $temp_code = $expect;
                                $this->saveLotteryCode($round_list, $index, $expect, $rs);
                            }
                        }
                        return false;


                    }
                });
            });


        }
    }

    protected function saveLotteryCode($round_list, $index, $expect, $rs)
    {
        $circle_data = [
            'type' => 'open_lottery',
            'content' => [
                'round_circle' => $round_list[$index - 1]['round_circle'],
                'lottery_number' => explode(',', $rs)
            ]
        ];

        // 创建开奖记录
        try {
            $this->db->where('round_qishu', date('Ymd') . $round_list[$index - 1]['round_circle']);
            $res = $this->db->getOne('game_round');
            if (empty($res)) {
                $data = [
                    'round_uuid' => UUID::v4(),
//                                'round_id'   => $room_list[$index-1]['round_id'],
                    'round_result' => $rs,
                    'round_turn' => $round_list[$index - 1]['round_circle'],
                    'year' => date('Y')
                    , 'month' => date('m'),
                    'day' => date('d'),
                    'round_qishu' => date('Ymd') . $round_list[$index - 1]['round_circle'],
                    'round_remote_turn' => $expect
                ];
                $this->db->insert('game_round', $data);
            }
        } catch (\Exception $e) {
            echo $e->getMessage();

        }
        $this->sendMessage(['payload' => json_encode($circle_data)]);
    }

    protected
    function getOpenLottery()
    {
        $this->db->where('name', 'open_token');
        $list = $this->db->getOne('settings');
        $token = $list['value'] ?: 'teb6b9e68536f635fk';
        $url = "http://a.apiplus.net/{$token}/cqssc-1.json";
        $res = new HttpRequest();
        $result = $res->request('get', $url);
        $lottery_result = json_decode($result->getBody(), true);
        $number = $lottery_result['data'][0]['opencode'];
        $round = $lottery_result['data'][0]['expect'];
        if (!$number) {
            return false;
        }
        return ['number' => $number, 'expect' => $round];
    }

    protected
    function sendMessage($taskData = [])
    {
        $users = [];
        $roomid = isset($taskData['room_id']) ? $taskData['room_id'] : 0;
        if (empty($roomid)) {
            $room_list = Cache::getInstance()->get('room_list');
            foreach ($room_list as $item => $value) {
                $user[] = GameLogic::selectRoomFd($value['room_uuid']);
            }
            if (!empty($user)) {
                if (count($user) == 1) {
                    $users = $user[0];
                } else {
                    $users = [];
                    foreach ($user as $items => $list) {
                        foreach ($list as $ii => $vv) {
                            $users[] = $vv;
                        }
                    }
                }
            }


        } else {
            $users = GameLogic::selectRoomFd($roomid);
        }

        /** @var \swoole_websocket_server $server */
        $server = ServerManager::getInstance()->getServer();
        foreach ($users as $userFd) {
            $connection = $server->connection_info($userFd);
            if ($connection['websocket_status'] == 3) { // 用户正常在线时可以进行消息推送
                $server->push($userFd, $taskData['payload']);
            }
        }
    }


    public
    function onReceive(string $str, ...$args)
    {
        // TODO: Implement onReceive() method.
    }

    public
    function onShutDown()
    {
        // TODO: Implement onShutDown() method.
    }
}